<!--入库验收-->
<template>
	<div>
		<cus-search style="min-width: 1200px; padding-bottom: 0">
			<cus-search-item>
				<Form
					:model="form"
					:label-width="80"
					ref="formValidate"
					@keydown.native.enter.prevent="onInit"
				>
					<FormItem label="单据日期" class="mr_48 mb_20">
						<DatePicker
							type="daterange"
							ref="formDate"
							transfer
							v-model="dateStr"
							format="yyyy-MM-dd"
							@on-change="onChange"
							placeholder="开始日期 - 结束日期"
							style="width: 200px"
						/>
					</FormItem>
					<FormItem label="入库单号" class="mr_48 mb_20" prop="storageNo">
						<Input
							placeholder="请输入入库单号"
							maxlength="20"
							clearable
							v-model="form.storageNo"
							style="width: 200px"
						/>
					</FormItem>
					<FormItem
						label="采购单号"
						:label-width="80"
						class="mr_48 mb_20"
						prop="billNo"
					>
						<Input
							placeholder="请输入采购单号"
							maxlength="20"
							clearable
							v-model="form.billNo"
							style="width: 200px"
						/>
					</FormItem>
					<FormItem label="供应商" class="mr_48 mb_20" prop="supplyId">
						<Select
							placeholder="请输入供应商"
							v-model="form.supplyId"
							clearable
							style="width: 200px"
						>
							<Option
								v-for="item in supplierNameTree"
								:value="item.id"
								:key="item.id"
								>{{ item.name }}</Option
							>
						</Select>
					</FormItem>
					<FormItem label="验收员" class="mr_48 mb_20" prop="checkName">
						<Input
							placeholder="请输入验收员"
							maxlength="20"
							clearable
							v-model="form.checkName"
							style="width: 200px"
						/>
					</FormItem>
					<FormItem
						label="入库方式"
						:label-width="80"
						class="mr_48 mb_20"
						prop="storageway"
					>
						<Select
							placeholder="全部"
							clearable
							v-model="form.storageway"
							style="width: 200px"
						>
							<Option
								v-for="item in storagewayTree"
								:value="item.code"
								:key="item.code"
								>{{ item.desc }}</Option
							>
						</Select>
					</FormItem>
					<cusButton
						class="mr_20 mb_20"
						type="primary"
						@onClick="
							pages.page = 1
							getGoodsStockbilListApi()
						"
						>查询</cusButton
					>
					<cusButton class="mr_20 mb_20" @onClick="reset()">重置</cusButton>
				</Form>
			</cus-search-item>
		</cus-search>
		<cus-card class="cus_cardBox" :showTitle="false">
			<div class="btnBox">
				<cusButton class="mr_20" type="primary" @onClick="onMterial()"
					>物资入库汇总表</cusButton
				>
				<Dropdown class="dropDownItem" trigger="click">
					<cusButton type="primary">
						入库补录
						<Icon type="ios-arrow-down"></Icon>
					</cusButton>
					<template #list>
						<DropdownMenu>
							<DropdownItem @click.native="onManual()">手工入库</DropdownItem>
							<DropdownItem divided @click.native="onPurchase()"
								>采购单入库</DropdownItem
							>
							<DropdownItem divided @click.native="onScanCode()"
								>配送单入库</DropdownItem
							>
						</DropdownMenu>
					</template>
				</Dropdown>
				<!-- <Poptip>
        <cusButton class="mr_10" type="primary"
          >入库补录
        </cusButton>
        <div slot="content">
          <cusButton class="mb_10" type="primary" @click.native="onManual()"
            >手工入库</cusButton
          >
          <cusButton class="mb_10" type="primary" @click.native="onPurchase()">采购单入库</cusButton>
          <cusButton class="mb_10" type="primary" @click.native="onScanCode()"
            >配送单入库</cusButton
          >
        </div>
      </Poptip> -->
			</div>
			<cusTable
				border
				:loading="form.loading"
				:columns="columns"
				:data="data"
				:size="vuex_config.tableSize"
				:bottomClass="['cus-page']"
			>
				<template slot-scope="{ row }" slot="billDateOperation">
					{{ new Date(row.billDate).Format('yyyy-MM-dd') }}
				</template>
				<template slot-scope="{ row }" slot="voucherOperation">
					<div class="flex" v-if="row.voucher">
						<cus-button
							type="text"
							size="small"
							:style="{ color: '#1E6FFF' }"
							@onClick="voucherShow(row)"
						>
							查看
						</cus-button>
					</div>
				</template>
				<template slot-scope="{ row }" slot="statusOperation">
					<div style="display: flex; justify-content: center">
						<div
							@click="coursePicShow(row)"
							v-if="row.coursePic"
							style="height: 40px; width: 80px"
						>
							<img
								:src="row.coursePic"
								alt=""
								style="height: 100%; width: 100%"
							/>
						</div>
					</div>
				</template>
				<template slot-scope="{ row }" slot="operation">
					<div class="flex">
						<cus-button
							type="text"
							size="small"
							:style="{ color: '#1E6FFF' }"
							style="padding: 0 5px"
							@onClick="onShow(row)"
						>
							<Icon type="ios-search" size="4" style="margin: 2px 3px 0 0" />
							<span>查看</span>
						</cus-button>
						<cus-button
							type="text"
							size="small"
							:style="{ color: '#1E6FFF' }"
							style="padding: 0 5px"
							@onClick="onTableExport(row)"
						>
							<Icon
								type="ios-download-outline"
								size="4"
								style="margin: 2px 3px 0 0"
							/>
							<span>导出</span>
						</cus-button>
						<cus-button
							type="text"
							size="small"
							:style="{ color: '#1E6FFF' }"
							style="padding: 0 5px"
							@onClick="onExportImage(row)"
							><Icon
								type="ios-download-outline"
								size="4"
								style="margin: 2px 3px 0 0"
							/>
							<span>导出验收称重照片</span>
						</cus-button>
						<cus-button
						    v-if="row.checkStatus == 0"
							type="text"
							size="small"
							:style="{ color: '#1E6FFF' }"
							style="padding: 0 5px"
							@onClick="onConfirm(row)"
						>

							<Icon
								
								type="md-cloud-download"
								size="4"
								style="margin: 2px 3px 0 0"
							/>
							<span>{{ '验收二维码' }} </span>
						</cus-button>
						<Poptip
						    v-else
							confirm
							:transfer="true"
							title="确认审核后，没上传的称重数据将无法上传"
							@on-ok="onConfirm(row)"
							width="210"
						>
						<cus-button
							type="text"
							size="small"
							:style="{ color: '#FF9900' }"
							style="padding: 0 5px"
							
							
						>
							<Icon
							
								type="ios-checkbox-outline"
								size="4"
								style="margin: 2px 3px 0 0"
							/>
							
							<span>{{ '确认' }} </span>
						</cus-button>
						</Poptip>
					</div>
				</template>
			</cusTable>
			<div class="cus_page">
				<cus-page
					:data="pages"
					class="mt_20"
					@pageChange="getGoodsStockbilListApi"
				></cus-page>
			</div>
		</cus-card>
		<!--手工入库-->
		<manualStorage ref="manualStorage"></manualStorage>
		<!--采购单入库-->
		<purchaseOrderReceipt ref="purchaseOrderReceipt"></purchaseOrderReceipt>
		<!--扫码配送入库-->
		<scanCode ref="scanCode"></scanCode>
		<!--查看入库过程图片-->
		<Modal v-model="photoModal" title="查看图片" width="800">
			<div>
				<img :src="photo" style="height: 100%; width: 100%" />
			</div>
			<div slot="footer">
				<slot name="footer">
					<div class="modal-footer"></div>
				</slot>
			</div>
		</Modal>
	</div>
</template>
<script>
import manualStorage from './components/manualStorage.vue'
import purchaseOrderReceipt from './components/purchaseOrderReceipt.vue'
import scanCode from './components/scanCode.vue'

import {
	getGoodsStockbilList,
	postGeneratePoStockbillIportExcel,
	postApiGoodsHandaworkCheckstockbill,
	getApiGoodsHandaworkSuppliername,
	getInStorageWays,
	getExportGoodsStockQrcode,
	onExportImage,
	valieDateExamine
} from '@/api/business/manager'

import axios from 'axios'
import moment, { RFC_2822 } from 'moment'
// require 方式
require('moment/locale/zh-cn')
moment.locale('zh-cn', {
	week: {
		dow: 1
	}
})
// import 方式
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const columns = [
	{
		title: '序号',
		type: 'index',
		align: 'center',
		minWidth: 70
	},
	{
		title: '入库单号',
		key: 'storageNo',
		minWidth: 145,
		align: 'center'
	},
	{
		title: '单据日期',
		slot: 'billDateOperation',
		minWidth: 135,
		align: 'center'
	},
	{
		title: '供应商',
		key: 'supplierName',
		minWidth: 135,
		align: 'center'
	},
	{
		title: '验收员',
		key: 'checkName',
		minWidth: 135,
		align: 'center'
	},
	{
		title: '入库方式',
		key: 'storageWayDesc',
		minWidth: 145,
		align: 'center'
	},
	{
		title: '状态',
		key: 'checkStatus',
		minWidth: 135,
		align: 'center',
		render: (h, params) => {
			return h('div', [
				h(
					'span',
					{
						style: {
							background: params.row.checkStatus == 0 ? '#19BE6B' : '#ED4014',
							color: '#FFFFFF',
							padding: '5px'
						}
					},
					params.row.checkStatus == 0 ? '确认' : '未确认'
				)
			])
		}
	},
	{
		title: '最新更新时间',
		key: 'updateTime',
		minWidth: 145,
		align: 'center'
	},
	{
		title: '凭证',
		slot: 'voucherOperation',
		key: 'voucher',
		minWidth: 135,
		align: 'center'
	},
	{
		title: '场景照片',
		slot: 'statusOperation',
		minWidth: 135,
		align: 'center'
	},
	{
		title: '操作',
		fixed: 'right', // 右侧固定
		slot: 'operation',
		align: 'center',
		minWidth: 300
	}
]
export default {
	components: {
		manualStorage,
		purchaseOrderReceipt,
		scanCode
	},
	data() {
		return {
			form: {
				startDate: '', // 开始日期
				stopDate: '', // 结束日期
				billNo: '', // 采购单号
				storageNo: '', // 入库单号
				supplyId: '', // 供应商id
				storageway: '', // 入库方式
				checkName: '', // 验收员
				loading: false
			},
			ruleValidate: {}, // rule验证
			dateStr: [], // 当前起止日期
			storagewayTree: [], // 入库方式Tree数据
			columns: columns, // 表头
			data: [], // 表格列表
			photoModal: false, // 查看照片modal
			photo: '', // 照片路径
			supplierNameTree: [], // 供应商Tree数据
			pages: {
				page: 1,
				pageSize: 10,
				pageTotal: 0
			},
			tableHeight: 0
		}
	},
	mounted() {
		setTimeout(() => {
			this.tableHeight = window.innerHeight - 490 // 表格自适应高度
		}, 100)
		window.addEventListener('resize', this.tableHeightChange, true)
		this.onInit()
	},
	destroyed() {
		window.removeEventListener('resize', this.tableHeightChange, true)
	},
	methods: {
		onExportImage(row) {
			onExportImage({ stockBillId: row.id }).then((res) => {
				this.$Message.success('验收照片导出成功.')
				let blob = new Blob([res], { type: `application/vnd.ms-excel` })
				let downloadElement = document.createElement('a')
				let href = window.URL.createObjectURL(blob)
				downloadElement.href = href
				downloadElement.download = row.billNo + '验收照片'
				document.body.appendChild(downloadElement)
				downloadElement.click()
				document.body.removeChild(downloadElement)
				window.URL.revokeObjectURL(href)
			})
		},

		tableHeightChange() {
			this.tableHeight = 0
			setTimeout(() => {
				this.tableHeight = window.innerHeight - 490 // 表格自适应高度
			}, 100)
		},
		onInit() {
			this.getCurrentWeek()
			this.getInStorageWaysApi()
			this.getGoodsStockbilListApi()
			this.getApiGoodsHandaworkSuppliernameApi()
		},
		// 重置搜索
		reset() {
			this.form.startDate = ''
			this.form.stopDate = ''
			this.form.billNo = ''
			this.form.storageNo = ''
			this.form.supplyId = ''
			this.form.storageway = ''
			this.form.checkName = ''
			this.form.loading = false
			this.dateStr = []
			// this.$refs.formDate.handleClear(); //清空时间
			this.$refs['formValidate'].resetFields()
			this.onInit()
		},
		// DatePicker事件(起止日期)
		sDateChange(date) {
			console.log(date)
			;(this.form.startDate = date[0]), //开始日期
				(this.form.stopDate = date[1]) //结束日期
			this.getGoodsStockbilListApi()
		},
		onChange(e) {
			this.dateStr = e
			;(this.form.startDate = e[0]), // 开始日期
				(this.form.stopDate = e[1]) // 结束日期
		},
		// 查看凭证
		voucherShow(v) {
			window.location.href = v.voucher
		},
		// 查看照片
		coursePicShow(v) {
			this.photoModal = true
			this.photo = v.coursePic
		},
		// 查看详情
		onShow(row) {
			console.log(row,'列表');
			
			this.$router.push({
				path: '/wrehousingDetails/wrehousingDetails',
				query: {
					billNo: row.storageNo, //采购单号
					checkName: row.checkName, //验收员
					supplierName: row.supplierName, //供应商
					createTime: row.createTime, //日期
					id: row.id,
					checkStatus: row.checkStatus, //入库方式
					storageway: row.storageway
				}
			})
		},
		downloadFile1(url, name) {
			url = url || ''
			name = name || ''
			let ele = document.createElement('a')
			ele.target = '_blank'
			ele.href = url
			ele.download = name
			ele.click()
			ele = null
		},

		// a链接导出方法
		downloadFromApi(url) {
			let that = this
			console.log(222, url)
			axios({
				url: url,
				method: 'get',
				data: {},
				responseType: 'blob', // 后台返回的数据会被强制转为blob类型
				complete: function (xhr, data) {
					// 获取相关Http Response header
					var wpoInfo = {
						// 文件名
						'content-disposition': xhr.getResponseHeader('content-disposition')
					}
					// 在这里，做想做的事。。。
				}
			}).then((res) => {
				console.log()
				console.log(res)
				let reader = new FileReader()
				reader.readAsText(res.data)
				reader.onload = function (result) {
					console.log(result)
					try {
						let resData = JSON.parse(result.target.result) // 解析对象成功，说明是json数据
						console.log(resData)
						if (resData.retCode == 2999) {
							that.$Message.error(resData.retMsg)
						}
					} catch (err) {
						// 解析成对象失败，说明是正常的文件流
						// console.log('报错', err);
						// let blob = new Blob([res], { type: "application/vnd.ms-excel" });
						// var link = document.createElement('a');
						// const dispoition = res.headers['content-disposition'] || ''
						// let nameStr = dispoition.split(';')[1] || ''
						// let fileNamec = decodeURIComponent(nameStr.split('=')[1] || '')
						// let fileName = decodeURI(escape(fileNamec))
						// link.href = window.URL.createObjectURL(blob);
						// link.download = fileName;
						// link.click()
						let blob = new Blob([res.data], {
							type: '.xlsx'
						})
						let contentDisposition = res.headers['content-disposition'] //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
						// let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
						// let result = patt.exec(contentDisposition);
						// console.log('12',decodeURI(result));
						// let thename = decodeURI(result[1]) //使用decodeURI对名字进行解码
						let nameStr = contentDisposition.split(';')[1] || ''
						let fileName = decodeURIComponent(nameStr.split('=')[1] || '');
						
						let downloadElement = document.createElement('a')
						let href = window.URL.createObjectURL(blob) //创建下载的链接
						downloadElement.style.display = 'none'
						downloadElement.href = href
						downloadElement.download = fileName //下载后文件名
						document.body.appendChild(downloadElement)
						downloadElement.click() //点击下载
						document.body.removeChild(downloadElement) //下载完成移除元素
						window.URL.revokeObjectURL(href) //释放掉blob对象
					}
				}
			})
		},

		// 导出excel报表数据
		onTableExport(row) {
			console.log(343434)
			// return new Promise(resolve => {
			//   postGeneratePoStockbillIportExcel({ stockId: row.id }).then(res => {
			//     if (res.retCode !== 2999) {
			//       this.$Message.success("导出中...");
			//       let blob = new Blob([res], { type: `application/vnd.ms-excel` });
			//       console.log(blob, 'blod')
			//       let downloadElement = document.createElement("a");
			//       let href = window.URL.createObjectURL(blob);
			//       downloadElement.href = href;
			//       downloadElement.download = "入库验收单";
			//       document.body.appendChild(downloadElement);
			//       downloadElement.click();
			//       document.body.removeChild(downloadElement);
			//       window.URL.revokeObjectURL(href);
			//       resolve();
			//     }
			//   });
			// });
			this.downloadFromApi(
				`${postGeneratePoStockbillIportExcel(row.id)}&token=${
					this.$store.state.vuex_user.token
				}`
			)
			// window.location.href = `${postGeneratePoStockbillIportExcel(row.id)}&token=${this.$store.state.vuex_user.token}`;
		},
		// 确认审核table单
		onConfirm(row) {
			console.log(row.checkStatus)
			if (row.checkStatus == 0) {
				this.$cu.debounce(() => {
					window.location.href = `${getExportGoodsStockQrcode(row.id)}&token=${
						this.$store.state.vuex_user.token
					}`
				})
			} else {
				this.$cu.debounce(() => {
					this.form.loading = true
					this.valieDateExamine(row)
				})
			}
		},
		//检验审核
		valieDateExamine(row) {
			valieDateExamine({ stockBillId: row.id }).then((res) => {
				if (res.retCode == 2000) {
					this.postApiGoodsHandaworkCheckstockbillApi(row.id)
				} else if (res.retCode == 2888) {
					let content = ''
					res.data.map((it) => {
						content += `<p style="margin-top:5px">${it}</p>`
					})
					this.$Modal.confirm({
						title: res.retMsg,
						content: content,
						width: '750',
						okText: '继续生成',
						onOk: () => {
							this.postApiGoodsHandaworkCheckstockbillApi(row.id)
						}
					})
				}
			})
		},

		// 手工入库事件
		onManual() {
			this.$refs['manualStorage'].show()
		},
		// 采购单入库
		onPurchase() {
			this.$refs['purchaseOrderReceipt'].show()
			this.$refs['purchaseOrderReceipt'].supplierNameTree =
				this.supplierNameTree
		},
		// 扫码配送入库
		onScanCode() {
			this.$refs['scanCode'].show()
		},
		// 物资入库汇总表
		onMterial() {
			this.$router.push({
				path: '/mterialWarehousing/mterialWarehousing'
			})
		},
		// 获取本周日期组件处理
		getCurrentWeek() {
			let start = moment().weekday(0).format('YYYY-MM-DD') //本周一
			let end = moment().weekday(6).format('YYYY-MM-DD') //本周日、
			this.dateStr = [start, end]
			// this.dateStr[0] = start; //默认一周开始时间
			// this.dateStr[1] = end; //默认一周结束时间
			this.form.startDate = start
			this.form.stopDate = end
			console.log(start, end)
			// 数组更新需要使用$set手动更新
			//       this.$set(this.dateStr,0,start)
			// this.$set(this.dateStr,1,end)
		},
		// 入库验收列表--------------------------接口
		getGoodsStockbilListApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				let params = {
					supplyId: this.form.supplyId,
					startDate: this.form.startDate,
					stopDate: this.form.stopDate,
					storageNo: this.form.storageNo,
					checkName: this.form.checkName,
					billNo: this.form.billNo,
					storageway: this.form.storageway,
					current: this.pages.page,
					size: this.pages.pageSize
				}
				getGoodsStockbilList(params).then((res) => {
					this.form.loading = false
					if (res.retCode === 2000) {
						this.data = res.data.records
						// this.data.forEach((element) => {
						// 	//入库方式 0 （电子秤采购入库） 1（手工入库）2（电子秤无单入库）3（冲销）4（补缴）5（电子秤采购越库）6（电子秤无单越库）7 (扫描配送单二维码生成)
						// 	// element.storageway =
						// 	// 	element.storageway == 0
						// 	// 		? '电子秤采购入库'
						// 	// 		: element.storageway == 1
						// 	// 		? '手工入库'
						// 	// 		: element.storageway == 2
						// 	// 		? '电子秤无单入库'
						// 	// 		: element.storageway == 3
						// 	// 		? '冲销'
						// 	// 		: element.storageway == 4
						// 	// 		? '补缴'
						// 	// 		: element.storageway == 5
						// 	// 		? '电子秤采购越库'
						// 	// 		: element.storageway == 6
						// 	// 		? '电子秤无单越库'
						// 	// 		: element.storageway == 7
						// 	// 		? '扫描配送单二维码生成'
						// 	// 		: element.storageway == 8
						// 	// 		? '采购单入库'
						// 	// 		: element.storageway == 9
						// 	// 		? '成品入库'
						// 	// 		: ''
						// })
						this.pages.pageTotal = res.data.total
						resolve()
					}
				})
			})
		},
		// 物资入库验收Table确认审核----------------------接口
		postApiGoodsHandaworkCheckstockbillApi(id) {
			return new Promise((resolve) => {
				postApiGoodsHandaworkCheckstockbill({ postockid: id }).then((res) => {
					this.form.loading = false
					if (res.retCode === 2000) {
						this.$Message.success(res.retMsg)
						this.getGoodsStockbilListApi()
						resolve()
					}
				})
			})
		},
		// 获取物资食材供应商名称---------------------------接口
		getApiGoodsHandaworkSuppliernameApi() {
			return new Promise((resolve) => {
				getApiGoodsHandaworkSuppliername().then((res) => {
					if (res.retCode === 2000) {
						this.supplierNameTree = res.data
						resolve()
					}
				})
			})
		},
		// 获取所有入库方式-------------------接口
		getInStorageWaysApi() {
			return new Promise((resolve) => {
				getInStorageWays().then((res) => {
					if (res.retCode === 2000) {
						this.storagewayTree = res.data
						resolve()
					}
				})
			})
		}
	}
}
</script>

<style lang="less" scoped>
.btnBox {
	padding-bottom: 20px;
	display: flex;
	justify-content: flex-end;
}
</style>
